//
//  CatVideoVController.m
//  DoorBell
//
//  Created by Chun Hung Cheung on 2023/3/17.
//  Copyright © 2023 Chun Hung Cheung. All rights reserved.
//

#import "CatVideoVController.h"
#import "CatFeedVController.h"
#import "CatSettinVController.h"
#import "CatTimingListVController.h"
#import "CatMessageVController.h"
#import <Photos/Photos.h>
#include <AssetsLibrary/AssetsLibrary.h>
@interface CatVideoVController ()

@property(nonatomic,strong)UIView  *topVideoContrainView;
@property(nonatomic,strong)UIButton *mesageButton;
@property(nonatomic,strong)UIButton *settingButton;
@property(nonatomic,strong)UILabel  *titleLabel;
@property(nonatomic,assign)BOOL iSAddButton;
@property(nonatomic,strong)UIImageView *offlineView;
@property(nonatomic,strong)UILabel *offlineLabel;
@property(nonatomic,copy)NSString *rtcip;
@property(nonatomic,assign)int rtcport;
@property(nonatomic,strong)UIImageView  *animationImageView;
@property(nonatomic,assign)BOOL videoFlag;
@property(nonatomic,assign)BOOL bopenMicro;
@property(nonatomic,assign)BOOL canPostVoice;
@property(nonatomic,strong)UILabel *contectingLabel;
@property(nonatomic,assign)int num;
@property(nonatomic,assign)int video_call_time;

/*定时器*/
@property (nonatomic,strong)dispatch_source_t e6_timer;
@property (nonatomic,strong)dispatch_source_t wake_up_timer;
@property (nonatomic,assign)BOOL cancelpost;

//图片的宽高比
@property(nonatomic,assign)float rateValue;
@property(nonatomic,assign)BOOL isSucessFlag;
@property(nonatomic,strong)FBDevicesList *devicesList;
@property(nonatomic,strong)NSTimer *timer;
@property(nonatomic,strong)NSDate *todate;
@property(nonatomic,assign)BOOL is_wake_up;
@property(nonatomic,assign)int over_99;
@property(nonatomic,assign)BOOL is_send_call;
@property(nonatomic,strong)NSTimer *waittingVideoTimer;//视频加载动画定时器
@property(nonatomic,strong)UIImageView  *video_contrainView;
@property(nonatomic,strong)UIButton  *play_button;
@property(nonatomic,assign)BOOL is_click_play;
@property(nonatomic,assign)BOOL is_entry_setting;
@property(nonatomic,assign)BOOL is_over_time;

@property(nonatomic,strong)UIButton *recording_button;
@property(nonatomic,assign)BOOL is_recording;

@end

@implementation CatVideoVController

- (void)viewDidLoad {
    [super viewDidLoad];
     self.view.backgroundColor = [HexChangeRGB colorWithHexString:@"#F1EFF0"];
     self.devicesList = [[FBDevicesList bg_find:@"FBDevicesList" where:[NSString stringWithFormat:@"where %@=%@ and %@=%@",bg_sqlKey(@"userName"),bg_sqlValue([Tooles getuserToken]), bg_sqlKey(@"bid"),bg_sqlValue(self.bid)]] firstObject];

    [[NSUserDefaults standardUserDefaults] setObject:@"0" forKey:@"isopenmicro"];
    [[NSUserDefaults standardUserDefaults] synchronize];
    
    [self setup];
     self.is_entry_setting = NO;
     self.is_over_time = NO;
     self.topVideoContrainView.backgroundColor = [UIColor blackColor];
    if (self.devicesList.status > 0) {
        UIImage *image = [UIImage imageNamed:@"cat_videoimg_default"];
        UIImage *image2 = [self get_image_album];
        UIImage *image3 = image2.size.width > 0 ? image2 : image;
        
        self.video_contrainView.image = image3;
        self.play_button.backgroundColor = [UIColor clearColor];
    }else{
        
        UIImage *image = [UIImage imageNamed:@"cat_videoimg_default_offline"];
        UIImage *image2 = [self get_image_album];
        UIImage *image3 = image2.size.width > 0 ? image2 : image;
        
        self.video_contrainView.image = image3;
        self.offlineView.image = [UIImage imageNamed:@"cat_wifi_none"];
        self.offlineLabel.text = NSLocalizedString(@"设备离线", nil);
    }
}

- (UIImageView*)video_contrainView
{
    if (!_video_contrainView) {
         _video_contrainView = [[UIImageView alloc]init];
         _video_contrainView.userInteractionEnabled = YES;
         _video_contrainView.contentMode = UIViewContentModeScaleAspectFill;
        [self.topVideoContrainView addSubview:_video_contrainView];
        [_video_contrainView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self.topVideoContrainView.mas_left);
            make.right.equalTo(self.topVideoContrainView.mas_right);
            make.top.equalTo(self.topVideoContrainView.mas_top);
            make.bottom.equalTo(self.topVideoContrainView.mas_bottom);
        }];
    }
    return _video_contrainView;
}


- (void)manual_feed:(NSNotification*)cation
{
    
    NSTimeInterval interval =  [[NSDate date] timeIntervalSince1970];
    
    FBDevicesList *list = [[FBDevicesList bg_find:@"FBDevicesList" where:[NSString stringWithFormat:@"where %@=%@ and %@=%@",bg_sqlKey(@"userName"),bg_sqlValue([Tooles getuserToken]), bg_sqlKey(@"bid"),bg_sqlValue(self.bid)]] firstObject];
     list.interval = interval;
    if ([list bg_saveOrUpdate]) {
        self.devicesList = [[FBDevicesList bg_find:@"FBDevicesList" where:[NSString stringWithFormat:@"where %@=%@ and %@=%@",bg_sqlKey(@"userName"),bg_sqlValue([Tooles getuserToken]), bg_sqlKey(@"bid"),bg_sqlValue(self.bid)]] firstObject];
    }
    [SVProgressHUD showSuccessWithStatus:NSLocalizedString(@"喂食成功", nil)];
    
    [self getdata];
}


- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    /*视频成功回调*/
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(RecvPlayingMessage:) name:equesOnMessageVideoplayingNotification object:nil];
    
    /*视频超时回调*/
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(RecvCallTimeoutMsg:) name:equesOnMessageVideocTimeOut object:nil];
    
    /*设备上下线*/
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(devstClick:) name:DEVST object:nil];
    
    /*喂食成功*/
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(manual_feed:) name:@"manual_feed" object:nil];
    

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getdata) name:@"alarmReloadData" object:nil];
    
    
    if(@available(iOS 15.0,*)){
       UINavigationBarAppearance *apperance=[[UINavigationBarAppearance alloc]init];
       apperance.backgroundColor = [UIColor whiteColor];//设置背景色
       self.navigationController.navigationBar.standardAppearance = apperance;
       self.navigationController.navigationBar.scrollEdgeAppearance = apperance;
    }
   
     self.navigationController.navigationBar.barTintColor = [UIColor whiteColor];

     self.is_send_call = NO;
     self.devicesList = [[FBDevicesList bg_find:@"FBDevicesList" where:[NSString stringWithFormat:@"where %@=%@ and %@=%@",bg_sqlKey(@"userName"),bg_sqlValue([Tooles getuserToken]), bg_sqlKey(@"bid"),bg_sqlValue(self.bid)]] firstObject];
     self.titleLabel.text = self.devicesList.nick.length > 0 ? self.devicesList.nick : NSLocalizedString(@"宠物喂食器", nil);;
    [self getdevices];
   
    self.devicesList = [[FBDevicesList bg_find:@"FBDevicesList" where:[NSString stringWithFormat:@"where %@=%@ and %@=%@",bg_sqlKey(@"userName"),bg_sqlValue([Tooles getuserToken]), bg_sqlKey(@"bid"),bg_sqlValue(self.bid)]] firstObject];
   [self setup];
    self.topVideoContrainView.backgroundColor = [UIColor blackColor];
   if (self.devicesList.status > 0) {
       
       self.video_contrainView.hidden = NO;
       UIImage *image = [UIImage imageNamed:@"cat_videoimg_default"];
       UIImage *image2 = [self get_image_album];
       UIImage *image3 = image2.size.width > 0 ? image2 : image;
       
       self.video_contrainView.image = image3;
       self.play_button.backgroundColor = [UIColor clearColor];
       self.play_button.hidden = NO;
   }else{
       
       self.video_contrainView.hidden = NO;
       UIImage *image = [UIImage imageNamed:@"cat_videoimg_default_offline"];
       UIImage *image2 = [self get_image_album];
       UIImage *image3 = image2.size.width > 0 ? image2 : image;
       
       self.video_contrainView.image = image3;
       self.offlineView.image = [UIImage imageNamed:@"cat_wifi_none"];
       self.offlineLabel.text = NSLocalizedString(@"设备离线", nil);
   }
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self addFourButton];
        [self getdata];
        if (self.is_entry_setting && self.devicesList.power_mode) {
            
            [self wake_up_device];
        }
        
    });
    
    self.titleLabel.text = self.devicesList.nick.length > 0 ? self.devicesList.nick : NSLocalizedString(@"宠物喂食器", nil);;
    if (self.devicesList.remoteupg == 1 || self.devicesList.remoteupg == 2) {
        [self.settingButton setImage:[UIImage imageNamed:@"cat_set_msg_new"] forState:UIControlStateNormal];;
    }else{
        [self.settingButton setImage:[UIImage imageNamed:@"cat_set_msg"] forState:UIControlStateNormal];;
    }
}

//获取喂食记录和喂食告警消息 显示红点
- (void)getdata
{
    
    //默认获取三天内的消息
    long long startTime =  [[Tooles dateToUnixTime:[NSDate date]] longLongValue] - 86399000*3;
    long long endTime = startTime + 86399000*4;
    [AFNHTTPSRequest httpsRequestWithUrl:[YKBusinessFramework getCatFeedRecordWithBid:self.bid startTime:startTime end_time:endTime] errorHint:^(id errorData) {
        NSLog(@"获取喂食记录-->%@",errorData);
        
    } result:^(id value) {
        NSLog(@"获取喂食记录 ＝ %@",value);
        if ([[value objectForKey:@"code"] intValue] == 0) {
            NSMutableArray *alarm = [value objectForKey:@"data"];
            if (alarm.count > 0) {
                NSDictionary *dict = [alarm firstObject];
                long long times = [[dict objectForKey:@"createTime"] longLongValue];
                if (self.devicesList.last_see_record != times) {
                    
                    UIButton *sender = (UIButton*)[self.view viewWithTag:226];
                    if (sender) {
                         sender.enabled = YES;
                        [sender setImage:[UIImage imageNamed:@"cat_feed_record_new"] forState:UIControlStateNormal];
                    }
                    
                }else{
                    
                    UIButton *sender = (UIButton*)[self.view viewWithTag:226];
                    if (sender) {
                         sender.enabled = YES;
                        [sender setImage:[UIImage imageNamed:@"cat_feed_record"] forState:UIControlStateNormal];
                    }
                }
            }
        }
    }];
        
    [AFNHTTPSRequest httpsRequestWithUrl:[YKBusinessFramework getE1proLockAlarmdWithLockid:self.bid startTime:startTime end_time:endTime offset:0 limit:0] errorHint:^(id errorData) {
        NSLog(@"获取警告数量失败-->%@",errorData);
    } result:^(id value) {
        NSLog(@"获取警告数量 ＝ %@",value);
        [SVProgressHUD dismiss];
        if ([[value objectForKey:@"code"] intValue] == 0) {
            NSMutableArray *alarm = [value objectForKey:@"list"];
            if (alarm.count > 0) {
                 NSDictionary *dict = [alarm firstObject];
                 long long times =  [[dict objectForKey:@"time"] longLongValue];
                 if (self.devicesList.last_see_alarm != times) {
                    UIButton *sender = (UIButton*)[self.view viewWithTag:227];
                    if (sender) {
                        sender.enabled = YES;
                       [sender setImage:[UIImage imageNamed:@"cat_alarm_msg_new"] forState:UIControlStateNormal];
                    }
                 }else{
                     UIButton *sender = (UIButton*)[self.view viewWithTag:227];
                     if (sender) {
                         sender.enabled = YES;
                        [sender setImage:[UIImage imageNamed:@"cat_alarm_msg"] forState:UIControlStateNormal];
                     }
                 }
            }
        }
    }];
    
}




- (void)wake_up_device
{
    
    if (self.is_click_play) {
        return;
    }
    
    self.is_click_play = YES;
    if (self.video_contrainView.hidden) {
        return;
    }
    self.video_contrainView.hidden = YES;
    self.play_button.hidden = YES;
    __weak CatVideoVController *weakSelf = self;
    self.is_send_call = NO;
    self.devicesList = [[FBDevicesList bg_find:@"FBDevicesList" where:[NSString stringWithFormat:@"where %@=%@ and %@=%@",bg_sqlKey(@"userName"),bg_sqlValue([Tooles getuserToken]), bg_sqlKey(@"bid"),bg_sqlValue(self.bid)]] firstObject];
    if (self.devicesList.status == 2) {
        
        self.is_wake_up = YES;
        self.contectingLabel.text = [NSString stringWithFormat:@"%@ %d%@",NSLocalizedString(@"正在安全连接中...", nil),1,@"%"];
        // 发送唤醒指令 收到结果后设置为空 如果为yes 则发送唤醒指令
        
        [self loadingForVideoAnimation];
        
        __block int timeout1 = 30; // 倒计时时间
        dispatch_queue_t queue1 = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0);
        _e6_timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue1);
        dispatch_source_set_timer(_e6_timer,dispatch_walltime(NULL, 0),500*NSEC_PER_MSEC, 0); //每0.5秒执行
        dispatch_source_set_event_handler(_e6_timer, ^{
            dispatch_async(dispatch_get_main_queue(), ^{
                timeout1--;
                [self arc4randomNuber];
            });
        });
          dispatch_resume(_e6_timer);
        
        // 发送唤醒指令 收到结果后设置为空 如果为yes 则发送唤醒指令
        __block int timeout = 30*200*5; // 倒计时时间
        _cancelpost = NO;
        dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
        _wake_up_timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
        dispatch_source_set_timer(_wake_up_timer,dispatch_walltime(NULL, 0),200.0*NSEC_PER_MSEC, 0); //每秒执行
        dispatch_source_set_event_handler(_wake_up_timer, ^{
            if(weakSelf.cancelpost){ // 倒计时结束，关闭
                dispatch_source_cancel(weakSelf.wake_up_timer);
                weakSelf.wake_up_timer = nil;
                if (!self.is_send_call) {
                    [self makecall];
                }
            }else{
                NSString *Str =   [NSString stringWithFormat:@"{\"method\":\"wake_up_t1_r700\",\"from\":\"%@\",\"to\":\"%@\",\"id\":100006071,\"value\": {\"id\":2,\"val\":1}}",[[NSUserDefaults standardUserDefaults] objectForKey:@"EquesUid"],self.bid];
                [YKBusinessFramework equesSendData:Str];
                 timeout-=200;
                if (timeout <= 0) {
                    dispatch_source_cancel(weakSelf.wake_up_timer);
                    weakSelf.wake_up_timer = nil;
                }
            }
        });
         dispatch_resume(_wake_up_timer);
    }else if (self.devicesList.status == 1){
        
         self.is_wake_up = NO;
         self.contectingLabel.text = [NSString stringWithFormat:@"%@ %d%@",NSLocalizedString(@"正在安全连接中...", nil),1,@"%"];
        [self loadingForVideoAnimation];
        // 发送唤醒指令 收到结果后设置为空 如果为yes 则发送唤醒指令
        __block int timeout = 30; // 倒计时时间
        dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0);
        _e6_timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
        dispatch_source_set_timer(_e6_timer,dispatch_walltime(NULL, 0),500*NSEC_PER_MSEC, 0); //每0.5秒执行
        dispatch_source_set_event_handler(_e6_timer, ^{
            dispatch_async(dispatch_get_main_queue(), ^{
                 timeout--;
                [self arc4randomNuber];
            });
        });
          dispatch_resume(_e6_timer);
         [self makecall];
        
    }else{
        
         self.is_wake_up = NO;
         self.contectingLabel.text = [NSString stringWithFormat:@"%@ %d%@",NSLocalizedString(@"正在安全连接中...", nil),1,@"%"];
        [self loadingForVideoAnimation];
        // 发送唤醒指令 收到结果后设置为空 如果为yes 则发送唤醒指令
        __block int timeout = 30; // 倒计时时间
        dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0);
        _e6_timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
        dispatch_source_set_timer(_e6_timer,dispatch_walltime(NULL, 0),500*NSEC_PER_MSEC, 0); //每0.5秒执行
        dispatch_source_set_event_handler(_e6_timer, ^{
            dispatch_async(dispatch_get_main_queue(), ^{
                 timeout--;
                
                [self arc4randomNuber];
                
                if (timeout <= 10) {

                    self.devicesList = [[FBDevicesList bg_find:@"FBDevicesList" where:[NSString stringWithFormat:@"where %@=%@ and %@=%@",bg_sqlKey(@"userName"),bg_sqlValue([Tooles getuserToken]), bg_sqlKey(@"bid"),bg_sqlValue(self.bid)]] firstObject];
                    
                    if (self.devicesList.status == 0) {
                        
                        if (weakSelf.contectingLabel) {
                           [weakSelf.contectingLabel removeFromSuperview];
                            weakSelf.contectingLabel = nil;
                        }
                        [self stop_animation];
                        self.offlineView.image = [UIImage imageNamed:@"cat_wifi_none"];
                        self.offlineLabel.text = NSLocalizedString(@"设备离线", nil);
                       [self.video_contrainView bringSubviewToFront:self.offlineView];
                       [self.video_contrainView bringSubviewToFront:self.offlineLabel];
                       
                        if(weakSelf.e6_timer){
                           dispatch_source_cancel(weakSelf.e6_timer);
                            weakSelf.e6_timer = nil;
                        }
                        
                    }else if (self.devicesList.status == 1){
                       
                        if (!self.is_send_call) {
                            [self makecall];
                        }
                    }else if (self.devicesList.status == 2){
                        
                        self.is_wake_up = YES;
        
                        // 发送唤醒指令 收到结果后设置为空 如果为yes 则发送唤醒指令
                        __block int timeout = 30*200*5; // 倒计时时间
                        weakSelf.cancelpost = NO;
                        dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
                        weakSelf.wake_up_timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
                        dispatch_source_set_timer(weakSelf.wake_up_timer,dispatch_walltime(NULL, 0),200.0*NSEC_PER_MSEC, 0); //每秒执行
                        dispatch_source_set_event_handler(weakSelf.wake_up_timer, ^{
                            if(weakSelf.cancelpost){ // 倒计时结束，关闭
                                dispatch_source_cancel(weakSelf.wake_up_timer);
                                weakSelf.wake_up_timer = nil;
                            }else{
                                NSString *Str =   [NSString stringWithFormat:@"{\"method\":\"wake_up_t1_r700\",\"from\":\"%@\",\"to\":\"%@\",\"id\":100006071,\"value\": {\"id\":2,\"val\":1}}",[[NSUserDefaults standardUserDefaults] objectForKey:@"EquesUid"],self.bid];
                                [YKBusinessFramework equesSendData:Str];
                                 timeout-=200;
                                if (timeout <= 0) {
                                    dispatch_source_cancel(weakSelf.wake_up_timer);
                                    weakSelf.wake_up_timer = nil;
                                }
                            }
                        });
                         dispatch_resume(weakSelf.wake_up_timer);
                    }
                }
                
            });
        });
          dispatch_resume(_e6_timer);

    }
}


- (void)loadingForVideoAnimation{


     self.animationImageView.animationImages = [NSArray arrayWithObjects:
                                   [UIImage imageNamed:@"annimation_new_loading_1"],
                                   [UIImage imageNamed:@"annimation_new_loading_2"],
                                   [UIImage imageNamed:@"annimation_new_loading_3"],
                                   [UIImage imageNamed:@"annimation_new_loading_4"],
                                   [UIImage imageNamed:@"annimation_new_loading_5"],
                                   [UIImage imageNamed:@"annimation_new_loading_6"],
                                   [UIImage imageNamed:@"annimation_new_loading_7"],
                                   [UIImage imageNamed:@"annimation_new_loading_8"],
                                   nil];

    self.animationImageView.animationDuration = 1.2;
    self.animationImageView.animationRepeatCount = 26;
   [self.animationImageView startAnimating];
     _waittingVideoTimer = [NSTimer scheduledTimerWithTimeInterval:30 target:self selector:@selector(loadingForVideoTimeOut) userInfo:nil repeats:NO];
    
}

- (void)loadingForVideoTimeOut
{
    NSLog(@"动画超时");
}

- (void)stop_animation
{
    
    [_waittingVideoTimer invalidate];
     _waittingVideoTimer = nil;
    
    if ([_animationImageView isAnimating]) {
        [_animationImageView stopAnimating];
        [_animationImageView removeFromSuperview];
         _animationImageView = nil;
    }
}

#pragma mark 视频拨打超时通知
- (void)RecvCallTimeoutMsg:(NSNotification*)notification
{
    dispatch_async(dispatch_get_main_queue(), ^{
        
        if (self.is_recording) {
            [self stop_record];
        }
        
        [self hangup:YES];
        
        __weak CatVideoVController *weakSelf = self;
        if(weakSelf.e6_timer){
           dispatch_source_cancel(weakSelf.e6_timer);
            weakSelf.e6_timer = nil;
        }
        [self stop_animation];
       
         self.contectingLabel.text = NSLocalizedString(@"查看失败，请退出重试～",nil);
       
    
        
        
        UIImageView *imageview = [[UIImageView alloc]init];
        imageview.tag = 12121;
        imageview.image = [UIImage imageNamed:@"cat_img_poor_wifi"];
       [self.topVideoContrainView  addSubview:imageview];
       [imageview mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(self.view.mas_centerX);
            make.height.mas_equalTo(132);
            make.width.mas_equalTo(127);
            make.top.equalTo(self.topVideoContrainView.mas_top).offset(135);
        }];
       
       [self.contectingLabel mas_remakeConstraints:^(MASConstraintMaker *make) {
           make.top.equalTo(imageview.mas_bottom).offset(10);
           make.centerX.equalTo(weakSelf.topVideoContrainView.mas_centerX);
       }];
       
        if(self.is_over_time){
            self.contectingLabel.text = NSLocalizedString(@"长时间未操作，请点击重试",nil);
        }else{
            self.contectingLabel.text = NSLocalizedString(@"网络开小差了，请点击重试",nil);
        }
       self.contectingLabel.textColor = [HexChangeRGB colorWithHexString:@"#cccccc"];
        
        UIButton *button2 = (UIButton*)[self.topVideoContrainView viewWithTag:38338];
        if (!button2) {
            UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
            button.tag = 38338;
           [button addTarget:self action:@selector(retryClick) forControlEvents:UIControlEventTouchUpInside];
            button.titleLabel.font = [UIFont fontWithName:@"PingFangSC-Medium" size:18];
           [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
           [self.topVideoContrainView  addSubview:button];
           [button mas_makeConstraints:^(MASConstraintMaker *make) {
                make.centerX.equalTo(self.topVideoContrainView.mas_centerX);
                make.top.equalTo(self.contectingLabel.mas_bottom).offset(20);
                make.height.mas_equalTo(44);
                make.width.mas_equalTo(160);
            }];
            button.layer.cornerRadius = 22;
            button.layer.borderWidth = 1.0;
            button.layer.borderColor = [HexChangeRGB colorWithHexString:@"#4D7CFE"].CGColor;
            button.layer.masksToBounds = YES;
            [button setTitle:NSLocalizedString(@"点击重试",nil) forState:UIControlStateNormal];
            [button setTitleColor:[HexChangeRGB colorWithHexString:@"#4D7CFE"] forState:UIControlStateNormal];
             
             if (weakSelf.play_button) {
                 [weakSelf.play_button removeFromSuperview];
                 weakSelf.play_button = nil;
             }
        }else{
            
            [button2 mas_remakeConstraints:^(MASConstraintMaker *make) {
                 make.centerX.equalTo(self.topVideoContrainView.mas_centerX);
                 make.top.equalTo(self.contectingLabel.mas_bottom).offset(20);
                 make.height.mas_equalTo(44);
                 make.width.mas_equalTo(160);
             }];
            
             if (weakSelf.play_button) {
                [weakSelf.play_button removeFromSuperview];
                 weakSelf.play_button = nil;
            }
        }
        
      
        
    });
}

-(void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
  
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    if([SVProgressHUD isVisible]){
       [SVProgressHUD dismiss];
    }
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"manual_feed" object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"devst" object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:equesOnMessageVideoplayingNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"timeout" object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"alarmReloadData" object:nil];
    
    // 如果不想让其他页面的导航栏变为透明 需要重置
    [self.navigationController.navigationBar setBackgroundImage:nil forBarMetrics:UIBarMetricsDefault];
    [self.navigationController.navigationBar setShadowImage:nil];
}





- (void)devstClick:(NSNotification*)notification
{
    /*
     {
         bid = 1fd834a600472ebe24cb01e03f9416d1;
         method = devst;
         name = "e0d31a150c6f-1fd834a6";
         remoteupg = 2;
         role = 27;
         status = 0;
         stat = 0;
         type = 27;
         uid = 1fd834a600472ebe24cb01e03f9416d1;
     }
    */
    NSLog(@"deist ---");
    NSDictionary *dict = (NSDictionary*)notification.object;
    NSString *bid = [dict objectForKey:@"bid"];
    if (![bid isEqualToString:self.bid]) {
         return;
    }

    if ([self.bid isEqualToString:bid] && [[dict objectForKey:@"stat"] intValue] == 1) {
        
         self.cancelpost = YES;
         if (!self.is_send_call) {
            if(_offlineView){
              [_offlineView removeFromSuperview];
               _offlineView = nil;
            }
           
           if(_offlineLabel){
             [_offlineLabel removeFromSuperview];
              _offlineLabel = nil;
           }
            self.play_button.backgroundColor = [UIColor clearColor];
         }

        
    }else if ([self.bid isEqualToString:bid] && [[dict objectForKey:@"stat"] intValue] == 0) {

        
        if (!self.is_send_call) {
            if(_play_button){
              [_play_button removeFromSuperview];
                _play_button = nil;
            }
            
            self.offlineView.image = [UIImage imageNamed:@"cat_wifi_none"];
            self.offlineLabel.text = NSLocalizedString(@"设备离线", nil);
            
        }
        
    
    }else if ([self.bid isEqualToString:bid] && [[dict objectForKey:@"stat"] intValue] == 2) {
        
        
        if (!self.is_send_call) {
            
            if(_offlineView){
              [_offlineView removeFromSuperview];
               _offlineView = nil;
            }
           
           if(_offlineLabel){
            [_offlineLabel removeFromSuperview];
             _offlineLabel = nil;
           }
            self.play_button.backgroundColor = [UIColor clearColor];
            
        }
    
    }
}


- (void)arc4randomNuber
{
   self.video_call_time ++;
   int i = 1 + (arc4random() % 3); // 1 - 8
   self.num = self.num + i;
   if (self.num >= 99) {
       self.num = 99;
       self.over_99 +=1;
   }
    if (self.over_99 < 3) {
        self.contectingLabel.text = [NSString stringWithFormat:@"%@ %d%@",NSLocalizedString(@"正在安全连接中...", nil),self.num,@"%"];
    }
   NSLog(@"video_call_time -->%d current progress -- %d%@ \n",self.video_call_time,self.num,@"%");
    
    if (self.over_99 == 2) {
        
        UIButton *button2 = (UIButton*)[self.topVideoContrainView viewWithTag:38338];
        if (button2) {
           [button2 removeFromSuperview];
            button2 = nil;
        }
        
        UIImageView *imageview2 = (UIImageView*)[self.topVideoContrainView viewWithTag:12121];
        if (imageview2) {
           [imageview2 removeFromSuperview];
            imageview2 = nil;
        }
        
        
        [self stop_animation];
         self.contectingLabel.text = NSLocalizedString(@"查看失败，请退出重试～",nil);
        
        UIImageView *imageview = [[UIImageView alloc]init];
         imageview.tag = 12121;
         imageview.image = [UIImage imageNamed:@"cat_img_poor_wifi"];
        [self.topVideoContrainView  addSubview:imageview];
        [imageview mas_makeConstraints:^(MASConstraintMaker *make) {
             make.centerX.equalTo(self.view.mas_centerX);
             make.height.mas_equalTo(132);
             make.width.mas_equalTo(127);
             make.top.equalTo(self.topVideoContrainView.mas_top).offset(135);
         }];
        
        [self.contectingLabel mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(imageview.mas_bottom).offset(10);
            make.centerX.equalTo(_topVideoContrainView.mas_centerX);
        }];
        
        self.contectingLabel.text = NSLocalizedString(@"网络开小差了，请点击重试",nil);
        self.contectingLabel.textColor = [HexChangeRGB colorWithHexString:@"#cccccc"];
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.tag = 38338;
       [button addTarget:self action:@selector(retryClick) forControlEvents:UIControlEventTouchUpInside];
        button.titleLabel.font = [UIFont fontWithName:@"PingFangSC-Medium" size:18];
       [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
       [self.topVideoContrainView  addSubview:button];
       [button mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(self.topVideoContrainView.mas_centerX);
            make.top.equalTo(self.contectingLabel.mas_bottom).offset(20);
            make.height.mas_equalTo(44);
            make.width.mas_equalTo(160);
        }];
        button.layer.cornerRadius = 22;
        button.layer.borderWidth = 1.0;
        button.layer.borderColor = [HexChangeRGB colorWithHexString:@"#4D7CFE"].CGColor;
        button.layer.masksToBounds = YES;
        [button setTitle:NSLocalizedString(@"点击重试",nil) forState:UIControlStateNormal];
        [button setTitleColor:[HexChangeRGB colorWithHexString:@"#4D7CFE"] forState:UIControlStateNormal];
    
        if (_play_button) {
           [_play_button removeFromSuperview];
            _play_button = nil;
        }
    }
    
}


- (void)retryClick
{
     if (_wake_up_timer) {
        dispatch_source_cancel(_wake_up_timer);
        _wake_up_timer = nil;
     }

    if(_e6_timer){
       dispatch_source_cancel(_e6_timer);
       _e6_timer = nil;
    }

    UIButton *button = (UIButton*)[self.topVideoContrainView viewWithTag:38338];
    if (button) {
       [button removeFromSuperview];
        button = nil;
    }
    
    UIImageView *imageview = (UIImageView*)[self.topVideoContrainView viewWithTag:12121];
    if (imageview) {
       [imageview removeFromSuperview];
        imageview = nil;
    }
    
     self.contectingLabel.textColor = [HexChangeRGB colorWithHexString:@"#ffffff"];
    [self.contectingLabel mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(_topVideoContrainView.mas_centerY);
        make.centerX.equalTo(_topVideoContrainView.mas_centerX);
    }];
    
     self.video_call_time = 0;
     self.video_contrainView.hidden = NO;
     self.is_click_play = NO;
     self.is_send_call = NO;
     self.over_99 = 0;
     self.isSucessFlag = NO;
     self.num = 0;
    [self wake_up_device];
}

#pragma mark 视频拨打成功
- (void)RecvPlayingMessage:(NSNotification *)notification
{
    NSLog(@"视频连接成功");
    
    __weak CatVideoVController *weakSelf = self;
    
    dispatch_async(dispatch_get_main_queue(), ^{
        
        [self stop_animation];
        UIButton *button = (UIButton*)[self.topVideoContrainView viewWithTag:38338];
        if (button) {
           [button removeFromSuperview];
           button = nil;
        }
        
        UIImageView *imageview = (UIImageView*)[self.topVideoContrainView viewWithTag:12121];
        if (imageview) {
           [imageview removeFromSuperview];
            imageview = nil;
        }
        self.todate  = [NSDate date];
        
        weakSelf.timer = [NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(timerFireMethod) userInfo:nil repeats:YES];
        [[NSRunLoop mainRunLoop] addTimer:weakSelf.timer forMode:NSDefaultRunLoopMode];
        
        
        int time =  self.is_wake_up ? 1 : 0;
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(time * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            if(weakSelf.e6_timer){
               dispatch_source_cancel(weakSelf.e6_timer);
                weakSelf.e6_timer = nil;
            }
            
            [self.contectingLabel removeFromSuperview];
             self.contectingLabel = nil;
             
            self.isSucessFlag = YES;
            
            self.canPostVoice = false;
            
            //默认关闭客户端给设备端的音量输出
            [YKBusinessFramework rtc_AudioPlayRecordEnable:false];
            
            [YKBusinessFramework rtc_AudioPlayEnable:weakSelf.bopenMicro];
            
            for (int i = 0; i < 8; i++) {
                UIButton *sender = (UIButton*)[self.view viewWithTag:222+i];
                if (sender) {
                    sender.enabled = YES;
                   [sender setTitleColor:[HexChangeRGB colorWithHexString:@"#666666"] forState:UIControlStateNormal];
                }
            }
        });
    });
    
}


#pragma  mark  超时
- (void)timerFireMethod
{
    NSCalendar *cal = [NSCalendar currentCalendar];//定义一个NSCalendar对象
    NSDate *today = [NSDate date];//得到当前时间
    unsigned int unitFlags2 = NSCalendarUnitSecond;
    NSDateComponents *s = [cal components:unitFlags2 fromDate:self.todate toDate:today options:0];
    NSLog(@"s.second--->%ld",(long)s.second);
    if (s.second == 210) {
        
        self.is_over_time = YES;
        [[NSNotificationCenter defaultCenter] postNotificationName:@"timeout" object:nil];
        
    }
}


    
    

- (void)makecall
{
    NSString *pathDocuments = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSString *imagePath = [NSString stringWithFormat:@"%@/YUV", pathDocuments];
    [[NSFileManager defaultManager] createDirectoryAtPath:imagePath withIntermediateDirectories:YES attributes:nil error:nil];
    NSString *tsfilePath = [imagePath stringByAppendingPathComponent:@"ceshi.yuv"];

    NSString *callMessag = [[NSUserDefaults standardUserDefaults] objectForKey:@"rtcserverip"];
    int port =  [[[NSUserDefaults standardUserDefaults] objectForKey:@"rtcserverport"] intValue];
    
    NSLog(@"callMessag -- %@ port == %d",callMessag,port);
    
    [[NSUserDefaults standardUserDefaults] synchronize];
    __weak CatVideoVController *weakSelf = self;
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        int status = -1;
        if (self.rtcip && self.rtcport) {
           // 初始化trc部分 VL1设备类型 必须处理
            status = [YKBusinessFramework rtc_initWithUserId:[[NSUserDefaults standardUserDefaults] objectForKey:@"EquesUid"] andIP:self.rtcip andPort:self.rtcport net_type:0];
        }else{
           // 初始化trc部分 VL1设备类型 必须处理
            status = [YKBusinessFramework rtc_initWithUserId:[[NSUserDefaults standardUserDefaults] objectForKey:@"EquesUid"] andIP:callMessag andPort:port net_type:0];
        }
        NSLog(@"rtc_initWithUserId status == %d",status);
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            if(status >= 0){
                NSLog(@"self.devicesList.standby3 --%@",self.devicesList.wifi_ssid);
                int camera_id;
                //是否已经获取到设备信息 如果获取到就读取获取的
                if (self.devicesList.wifi_ssid.length > 0) {
                    camera_id = self.devicesList.camera_id;
                }else{
                    camera_id = 1;
                }
                NSLog(@"camera_id --%d",camera_id);
                self.is_send_call = YES;
                [YKBusinessFramework rtc_make_Call:self.bid showView:weakSelf.topVideoContrainView peer_id:@"" camera_width:self.devicesList.videocall_width camera_height:self.devicesList.videocall_height isInvite:YES userID:[Tooles get_uid]  type:24002 path:tsfilePath isH264:NO camera_id:camera_id denoise:0  op_type:0 dataBlock:^(char *picdata, int data_size, int yuv_wdith, int yuv_height, const uint8_t *src_y, int src_stride_y, const uint8_t *src_u, int src_stride_u, const uint8_t *src_v, int src_stride_v) {
                }];
            }
        });
     });
}
    
// 截取 UIView 的方法
- (UIImage *)screenshotOfView:(UIView *)view {
    
    // 获取主屏幕对象
    UIScreen *mainScreen = [UIScreen mainScreen];
    // 获取当前屏幕的缩放因子（scale）
    CGFloat screenScale = mainScreen.scale;

    NSLog(@"当前屏幕的缩放因子为：%.2f", screenScale);

    UIGraphicsBeginImageContextWithOptions(view.bounds.size, NO, screenScale);
    [view drawViewHierarchyInRect:view.bounds afterScreenUpdates:YES];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}



- (void)save_image_album
{
    
    UIImage *image = [self capture];
    
    NSString *pathPrefix = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES) objectAtIndex:0];
    NSString *saveTo = [[pathPrefix stringByAppendingPathComponent:@"CATImage"] stringByAppendingPathComponent:self.bid];
    NSFileManager *fm = [NSFileManager defaultManager];
    if ([fm fileExistsAtPath:saveTo]) {

        //设置一个图片的存储路径
        NSString *imagePath = [saveTo stringByAppendingPathComponent:@"holder.jpg"];

        //把图片直接保存到指定的路径（同时应该把图片的路径imagePath存起来，下次就可以直接用来取）
        [UIImagePNGRepresentation(image) writeToFile:imagePath atomically:YES];

    }else{

        BOOL isS = [fm createDirectoryAtPath:saveTo withIntermediateDirectories:YES attributes:nil error:nil];
        if (isS) {
            NSLog(@"路径不存在创建成功");

            //设置一个图片的存储路径
            NSString *imagePath = [saveTo stringByAppendingPathComponent:@"holder.jpg"];

            //把图片直接保存到指定的路径（同时应该把图片的路径imagePath存起来，下次就可以直接用来取）
            [UIImagePNGRepresentation(image) writeToFile:imagePath atomically:YES];
        }
    }
}

- (UIImage *)get_image_album
{
    NSString *pathPrefix = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES) objectAtIndex:0];
    NSString *saveTo = [[pathPrefix stringByAppendingPathComponent:@"CATImage"] stringByAppendingPathComponent:self.bid];
    //设置一个图片的存储路径
    NSString *imagePath = [saveTo stringByAppendingPathComponent:@"holder.jpg"];
    
    UIImage *image = [UIImage imageWithContentsOfFile:imagePath];
  
    return image;
}

    

#pragma mark 抓拍处理
-(UIImage*)capture{
  
    UIImage *image = [self screenshotOfView:self.topVideoContrainView];
    
    NSLog(@"image---%@",image);

    return image;
}

- (void)deleteCapturepath{
    //获取Documents文件夹目录
    NSArray  *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentPath = [path objectAtIndex:0];
    //获取文件管理器
    NSFileManager *fileManager = [NSFileManager defaultManager];
    //指定新建文件夹路径
    NSString *imageDocPath = [documentPath stringByAppendingPathComponent:@"ImageFile"];
    //创建ImageFile文件夹
    [fileManager createDirectoryAtPath:imageDocPath withIntermediateDirectories:YES attributes:nil error:nil];
    
    NSString * capture = @"capture.jpg";
    NSString *newstr = [imageDocPath stringByAppendingFormat:@"/%@",capture];
    if ([[NSFileManager defaultManager]fileExistsAtPath:newstr]) {
        if([fileManager removeItemAtPath:newstr error:nil]){
            NSLog(@"删除抓拍路径删除成功");
        }else{
            [fileManager removeItemAtPath:newstr error:nil];
        }
    }
}
    

- (void)setup
{
     UIButton *backbtn = [UIButton buttonWithType:UIButtonTypeCustom];
     backbtn.frame = CGRectMake(0,0,60,80);
     backbtn.contentHorizontalAlignment =  UIControlContentHorizontalAlignmentLeft;
    [backbtn setImage:[UIImage imageNamed:@"cat_alarm_back"] forState:UIControlStateNormal];
    [backbtn addTarget:self action:@selector(selectLeftActionClick) forControlEvents:UIControlEventTouchUpInside];
    [backbtn SG_imagePositionStyle:SGImagePositionStyleDefault spacing:5];
     self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backbtn];
 
    self.titleLabel  = [[UILabel alloc]init];
    self.titleLabel.textColor = [HexChangeRGB colorWithHexString:@"#333333"];//[HexChangeRGB colorWithHexString:@"#333333"];
    self.titleLabel.font = [UIFont fontWithName:@"PingFangSC-Medium" size:20.0];
    self.titleLabel.text = self.devicesList.nick.length > 0 ? self.devicesList.nick : NSLocalizedString(@"宠物喂食器", nil);;
    self.titleLabel.textAlignment = NSTextAlignmentCenter;
    self.titleLabel.frame = CGRectMake(0, 0, 80, 25);
    self.navigationItem.titleView = self.titleLabel;

     self.settingButton = [UIButton buttonWithType:UIButtonTypeCustom];
     self.settingButton.frame = CGRectMake(0,0,25,25);
    
    if (self.devicesList.remoteupg == 1 || self.devicesList.remoteupg == 2) {
        [self.settingButton setImage:[UIImage imageNamed:@"cat_set_msg_new"] forState:UIControlStateNormal];;
    }else{
        [self.settingButton setImage:[UIImage imageNamed:@"cat_set_msg"] forState:UIControlStateNormal];;
    }
    
    [self.settingButton addTarget:self action:@selector(settingBtnActionClick) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *item2 = [[UIBarButtonItem alloc]initWithCustomView:self.settingButton];
    self.navigationItem.rightBarButtonItems = [NSArray arrayWithObjects:item2,nil];
}

- (void)selectLeftActionClick
{
    
    if (self.is_recording) {
        [self stop_record];
    }

    if (self.isSucessFlag || self.is_click_play) {
        [self hangup:NO];
    }
    
    [self.navigationController popViewControllerAnimated:YES];

}

- (void)hangup:(BOOL)over_time
{
    
    if (_timer) {
       [_timer invalidate];
        _timer = nil;
        
        self.is_over_time = NO;
    }
    
    if (self.isSucessFlag) {
        [self save_image_album];
    }
    
    if (_wake_up_timer) {
        dispatch_source_cancel(_wake_up_timer);
        _wake_up_timer = nil;
    }
    
    [self stop_animation];
    
    self.is_send_call = NO;
    self.over_99 = 0;
    self.isSucessFlag = NO;
    self.num = 0;
    self.is_click_play = NO;
 
     if(_e6_timer){
       dispatch_source_cancel(_e6_timer);
       _e6_timer = nil;
     }
    
    if(_contectingLabel){
     [_contectingLabel removeFromSuperview];
      _contectingLabel = nil;
    }
    
    self.isSucessFlag = NO;

    dispatch_async(dispatch_get_main_queue(), ^{

        if (!over_time) {
            [self removeFourButton];
             self.iSAddButton = NO;
        }
        
        [YKBusinessFramework rtc_hangup:self.bid];
        [YKBusinessFramework rtc_changSound:0];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            // 在这里放置原始代码
            [YKBusinessFramework rtc_uninit];
        });
        
    });
}


- (void)settingBtnActionClick
{
    CatSettinVController *setting = [[CatSettinVController alloc]init];
    setting.is_sucess = self.isSucessFlag;
    setting.bid = self.bid;
    if (self.is_recording) {
       [self stop_record];
    }
    if (self.is_click_play || self.isSucessFlag) {
        self.is_entry_setting = YES;
       [self hangup:NO];
    }
    if(![self.navigationController.topViewController isKindOfClass:[CatSettinVController class]]) {
       [self.navigationController pushViewController:setting animated:YES];
    }
}




- (UIImageView*)offlineView
{
    if(!_offlineView){
         _offlineView = [[UIImageView alloc]init];
        [self.video_contrainView addSubview:_offlineView];
        [_offlineView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(self.video_contrainView.mas_centerX);
            make.centerY.equalTo(self.video_contrainView.mas_centerY);
            make.width.mas_equalTo(60);
            make.height.mas_equalTo(55);
        }];
    }
    return _offlineView;
}

- (UILabel*)offlineLabel
{
    if (!_offlineLabel) {
         _offlineLabel = [[UILabel alloc]init];
         _offlineLabel.textAlignment = NSTextAlignmentCenter;
         _offlineLabel.textColor = [HexChangeRGB colorWithHexString:@"#ffffff"];
         _offlineLabel.font = [UIFont fontWithName:@"PingFangSC-Regular" size:18.0];
        [self.video_contrainView addSubview:_offlineLabel];
        [_offlineLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(self.video_contrainView.mas_centerX);
            make.top.equalTo(self.offlineView.mas_bottom).offset(20);
        }];
    }
    return _offlineLabel;
}

- (UIButton*)play_button
{
    if (!_play_button) {
        _play_button = [[UIButton alloc]init];
       [_play_button setImage:[UIImage imageNamed:@"cat_video_play"] forState:UIControlStateNormal];
       [_play_button addTarget:self action:@selector(play_button_click:) forControlEvents:UIControlEventTouchUpInside];
       [self.video_contrainView  addSubview:_play_button];
       [_play_button mas_makeConstraints:^(MASConstraintMaker *make) {
           make.height.mas_equalTo(60);
           make.width.mas_equalTo(60);
           make.centerX.equalTo(self.video_contrainView.mas_centerX);
           make.centerY.equalTo(self.video_contrainView.mas_centerY);
        }];
    }
    
    return _play_button;
}

- (void)play_button_click:(UIButton*)sender
{
    sender.selected = !sender.selected;
    
    [self wake_up_device];
}

- (UIView*)topVideoContrainView
{
    if(!_topVideoContrainView){
         _topVideoContrainView = [[UIView alloc]init];
         _topVideoContrainView.userInteractionEnabled = YES;
        [self.view addSubview:_topVideoContrainView];
        [_topVideoContrainView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self.view.mas_left);
            make.width.mas_equalTo(kScreenWidth);
            make.top.equalTo(self.view.mas_top).offset([UIDevice dev_navigationBarHeight]);
            make.height.mas_equalTo(kScreenWidth*1.33);
        }];
    }
    return _topVideoContrainView;
}

- (void)addFourButton
{
    if (self.iSAddButton) {
        return;
    }
    self.iSAddButton = YES;
    NSArray *iamgeArray = @[@"cat_btn_photo",@"cat_video_record",@"cat_btn_voice",@"cat_mute_on",@"cat_feed_record",@"cat_alarm_msg",@"cat_feed_plan",@"cat_btn_feed"];
    NSArray *iamgeSeltecdArray = @[@"cat_btn_photo_on",@"cat_video_record_on",@"cat_btn_voice_on",@"cat_feed_record_on",@"cat_alarm_msg_on",@"cat_feed_plan_on",@"cat_btn_feed_on"];
    NSArray *titleArray = @[NSLocalizedString(@"抓拍", nil),NSLocalizedString(@"录像", nil),NSLocalizedString(@"语音", nil),NSLocalizedString(@"声音", nil),NSLocalizedString(@"喂食记录", nil),NSLocalizedString(@"告警消息", nil),NSLocalizedString(@"喂食计划", nil),NSLocalizedString(@"加餐", nil)];
    NSArray *title_edArray = @[NSLocalizedString(@"抓拍", nil),NSLocalizedString(@"录像", nil),NSLocalizedString(@"语音", nil),NSLocalizedString(@"声音", nil),NSLocalizedString(@"喂食记录", nil),NSLocalizedString(@"告警消息", nil),NSLocalizedString(@"喂食计划", nil),NSLocalizedString(@"加餐", nil)];
    int wight = 60;
    int height = 80;
    int leghtMargin = (kScreenWidth - 4 * wight)/5;
    
   
    CGFloat y = CGRectGetMaxY(self.topVideoContrainView.frame);

    CGFloat topmargin = (kScreenHeight - y - 180)/3;
    NSLog(@"topmargin2 --%f",topmargin);
    
    //超过屏幕的尺寸
    if (topmargin < 0) {
        topmargin = 0;
    }
    
    for (int i = 0; i < 8; i ++) {
        
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.titleLabel.font = [UIFont fontWithName:@"PingFangSC-Regular" size:14];
       [button setTitleColor:[HexChangeRGB colorWithHexString:@"#666666"] forState:UIControlStateNormal];
        button.tag = 222+i;
       [self.view  addSubview:button];
       [button mas_makeConstraints:^(MASConstraintMaker *make) {
            
           make.height.mas_equalTo(height);
           make.width.mas_equalTo(wight);
           if (i > 3) {
               make.top.equalTo(self.topVideoContrainView.mas_bottom).offset(topmargin*2 + height);
               make.left.equalTo(self.view.mas_left).offset(leghtMargin + (i-4)*(wight+leghtMargin));
           }else{
               make.top.equalTo(self.topVideoContrainView.mas_bottom).offset(topmargin);
               make.left.equalTo(self.view.mas_left).offset(leghtMargin + i*(wight+leghtMargin));
               
           }
        }];
        
        if(i == 2){
            if(self.canPostVoice){
                [button setImage:[UIImage imageNamed:iamgeSeltecdArray[i]] forState:UIControlStateNormal];
            }else{
                [button setImage:[UIImage imageNamed:iamgeArray[i]] forState:UIControlStateNormal];
            }
            [button setTitle:titleArray[i] forState:UIControlStateNormal];
            [button setImage:[UIImage imageNamed:iamgeArray[i]] forState:UIControlStateNormal];
        }else if (i == 3){
            NSString *strMicrophone = [[NSUserDefaults standardUserDefaults] objectForKey:@"isopenmicro"];
           if(strMicrophone == nil){
                _bopenMicro = true;
               [button setImage:[UIImage imageNamed:@"cat_mute_on"] forState:UIControlStateNormal];
               [button setTitle:titleArray[i] forState:UIControlStateNormal];
           }else if ([strMicrophone isEqualToString:@"0"]) {
               [button setImage:[UIImage imageNamed:@"cat_mute_off"] forState:UIControlStateNormal];
                _bopenMicro = false;
               [button setTitle:title_edArray[i] forState:UIControlStateNormal];
           }else{
               [button setImage:[UIImage imageNamed:@"cat_mute_on"] forState:UIControlStateNormal];
                _bopenMicro = true;
               [button setTitle:titleArray[i] forState:UIControlStateNormal];
           }
        }
        else{
            [button setImage:[UIImage imageNamed:iamgeArray[i]] forState:UIControlStateNormal];
            [button setTitle:titleArray[i] forState:UIControlStateNormal];
        }
        
        if (i < 4) {
             button.enabled = self.isSucessFlag;
            [button setTitleColor:[HexChangeRGB colorWithHexString:@"#cccccc"] forState:UIControlStateNormal];
        }else{
            if (self.devicesList.status == 0) {
                if(i != 4 && i != 5){
                     button.enabled = self.isSucessFlag;
                    [button setTitleColor:[HexChangeRGB colorWithHexString:@"#cccccc"] forState:UIControlStateNormal];
                }
            }
        }
     
        [button SG_imagePositionStyle:SGImagePositionStyleTop spacing:6];
        [button addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchUpInside];
        [self.view bringSubviewToFront:button];
    }
}

- (UIButton*)recording_button
{
    if (!_recording_button) {
         _recording_button = [[UIButton alloc]init];
        [_recording_button setImage:[UIImage imageNamed:@"cat_record_oval"] forState:UIControlStateNormal];
        [_recording_button setTitleColor:[HexChangeRGB colorWithHexString:@"#ffffff"] forState:UIControlStateNormal];
         _recording_button.titleLabel.font = [UIFont fontWithName:@"PingFangSC-Regular" size:16.0];
        [self.topVideoContrainView  addSubview:_recording_button];
        [_recording_button mas_makeConstraints:^(MASConstraintMaker *make) {
           make.height.mas_equalTo(30);
           make.width.mas_equalTo(100);
           make.top.equalTo(self.topVideoContrainView.mas_top).offset(20);
           make.centerX.equalTo(self.topVideoContrainView.mas_centerX);
        }];
        _recording_button.layer.cornerRadius = 15;
        _recording_button.layer.masksToBounds = YES;
        _recording_button.backgroundColor = WXHColor(0, 0, 0, 0.5);
        [_recording_button SG_imagePositionStyle:SGImagePositionStyleDefault spacing:5];
    }
    
    return _recording_button;
}



- (void)buttonClick:(UIButton*)sender
{
   
    sender.selected = !sender.selected;
    switch (sender.tag) {
        case 222:
        {
            if(!self.isSucessFlag){
                return;
            }
            
            NSLog(@"点击拍照");
            if (!self.isSucessFlag) {
                return;
            }
            [SVProgressHUD show];
           
            UIImage *image = [self capture];
            
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                  
                [SVProgressHUD dismiss];

                [self saveImageToPhotos:image];
            });
        }
            break;
        case 223:
        {
            if(!self.isSucessFlag){
                return;
            }
            
            NSLog(@"点击录像");
        
            if (sender.selected) {
                [self start_record];
                [sender setImage:[UIImage imageNamed:@"cat_video_record_on"]forState:UIControlStateNormal];
                
                [self.recording_button setTitle:NSLocalizedString(@"正在录像", nil) forState:UIControlStateNormal];
                [self.topVideoContrainView bringSubviewToFront:self.recording_button];
            }else{
                [self stop_record];
                [sender setImage:[UIImage imageNamed:@"cat_video_record"] forState:UIControlStateNormal];
                
                [_recording_button removeFromSuperview];
                 _recording_button = nil;
            }
        
        }
            break;
        case 224:
        {
            if(!self.isSucessFlag){
                return;
            }
            
            NSLog(@"点击麦克风");
            self.canPostVoice = !self.canPostVoice;
            if(self.canPostVoice){
                [sender setImage:[UIImage imageNamed:@"cat_btn_voice_on"]forState:UIControlStateNormal];
            }else{
                [sender setImage:[UIImage imageNamed:@"cat_btn_voice"] forState:UIControlStateNormal];
            }
            [YKBusinessFramework rtc_AudioPlayEnable:_bopenMicro];
            [YKBusinessFramework rtc_AudioPlayRecordEnable:self.canPostVoice];
            
            [sender setTitle:NSLocalizedString(@"语音", nil) forState:UIControlStateNormal];
            [sender SG_imagePositionStyle:SGImagePositionStyleTop spacing:6];
            
        }
            break;
        case 225:
        {
            if(!self.isSucessFlag){
                return;
            }
            
            _bopenMicro = !_bopenMicro;
            NSString *str;
           [YKBusinessFramework rtc_AudioPlayEnable:_bopenMicro];
           if(_bopenMicro){
               [sender setImage:[UIImage imageNamed:@"cat_mute_on"] forState:UIControlStateNormal];
               str =  NSLocalizedString(@"语音", nil);
           }else{
               [sender setImage:[UIImage imageNamed:@"cat_mute_off"] forState:UIControlStateNormal];
               str = NSLocalizedString(@"静音", nil);
           }
            
            [sender setTitle:str forState:UIControlStateNormal];
            [sender SG_imagePositionStyle:SGImagePositionStyleTop spacing:10];
     
        }
            break;
            
        case 229:
        {
            
            NSLog(@"点击喂食");
            self.devicesList = [[FBDevicesList bg_find:@"FBDevicesList" where:[NSString stringWithFormat:@"where %@=%@ and %@=%@",bg_sqlKey(@"userName"),bg_sqlValue([Tooles getuserToken]), bg_sqlKey(@"bid"),bg_sqlValue(self.bid)]] firstObject];
            
            NSTimeInterval interval =  [[NSDate date] timeIntervalSince1970];
            
            __weak CatVideoVController *weakSelf = self;
            if (interval - self.devicesList.interval < 300) {
                
                UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"提示", nil) message:@"5分钟内已经投喂过，确定再次投喂？" preferredStyle:UIAlertControllerStyleAlert];
                UIAlertAction *cancelButton = [UIAlertAction actionWithTitle:NSLocalizedString(@"取消", nil) style:UIAlertActionStyleCancel handler:nil];
                UIAlertAction *deleteButton = [UIAlertAction actionWithTitle:NSLocalizedString(@"确定", nil) style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
                   
                    CatFeedVController *feedvc = [[CatFeedVController alloc] initWithType:kWHCustomAnimationTypePush];
                    feedvc.view.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:.4];
                    feedvc.definesPresentationContext = YES;
                    feedvc.modalPresentationStyle = UIModalPresentationOverCurrentContext;
                    feedvc.weightblock = ^(NSInteger weight) {
                        
                        self.devicesList = [[FBDevicesList bg_find:@"FBDevicesList" where:[NSString stringWithFormat:@"where %@=%@ and %@=%@",bg_sqlKey(@"userName"),bg_sqlValue([Tooles getuserToken]), bg_sqlKey(@"bid"),bg_sqlValue(self.bid)]] firstObject];
                        if (self.devicesList.status == 1) {
                            
                            [SVProgressHUD showTitle:NSLocalizedString(@"投喂中", nil) duration:2];
                           
                            NSLog(@"喂食 %ld 份",weight);
                            NSString *data = [NSString stringWithFormat:@"{\"method\":\"control\",\"to\":\"%@\",\"manual_feed\":%ld}",self.bid,weight];
                            [YKBusinessFramework equesSendData:data];
                            
                        }else if (self.devicesList.status == 2){
                            
                            [SVProgressHUD showTitle:NSLocalizedString(@"投喂中", nil) duration:2];
                       
                            __block int timeout = 30*200*5; // 倒计时时间
                            weakSelf.cancelpost = NO;
                            dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
                            weakSelf.wake_up_timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
                            dispatch_source_set_timer(weakSelf.wake_up_timer,dispatch_walltime(NULL, 0),200.0*NSEC_PER_MSEC, 0); //每秒执行
                            dispatch_source_set_event_handler(weakSelf.wake_up_timer, ^{
                                if(weakSelf.cancelpost){ // 倒计时结束，关闭
                                    dispatch_source_cancel(weakSelf.wake_up_timer);
                                    weakSelf.wake_up_timer = nil;
                                    
                                    NSLog(@"喂食 %ld 份",weight);
                                    NSString *data = [NSString stringWithFormat:@"{\"method\":\"control\",\"to\":\"%@\",\"manual_feed\":%ld}",self.bid,weight];
                                    [YKBusinessFramework equesSendData:data];
                                    
                                }else{
                                    NSString *Str =   [NSString stringWithFormat:@"{\"method\":\"wake_up_t1_r700\",\"from\":\"%@\",\"to\":\"%@\",\"id\":100006071,\"value\": {\"id\":2,\"val\":1}}",[[NSUserDefaults standardUserDefaults] objectForKey:@"EquesUid"],self.bid];
                                    [YKBusinessFramework equesSendData:Str];
                                     timeout-=200;
                                    if (timeout <= 0) {
                                        dispatch_source_cancel(weakSelf.wake_up_timer);
                                        weakSelf.wake_up_timer = nil;
                                    }
                                }
                            });
                             dispatch_resume(weakSelf.wake_up_timer);
                            
                        }
                        
                    };
                    
                   [self presentViewController:feedvc animated:YES completion:nil];
                    
                }];
               
                [alertController addAction:cancelButton];
                [alertController addAction:deleteButton];
                [self presentViewController:alertController animated:YES completion:nil];
                
                
            }else{
                
                CatFeedVController *feedvc = [[CatFeedVController alloc] initWithType:kWHCustomAnimationTypePush];
                feedvc.view.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:.4];
                feedvc.definesPresentationContext = YES;
                feedvc.modalPresentationStyle = UIModalPresentationOverCurrentContext;
                feedvc.weightblock = ^(NSInteger weight) {

                    
                    self.devicesList = [[FBDevicesList bg_find:@"FBDevicesList" where:[NSString stringWithFormat:@"where %@=%@ and %@=%@",bg_sqlKey(@"userName"),bg_sqlValue([Tooles getuserToken]), bg_sqlKey(@"bid"),bg_sqlValue(self.bid)]] firstObject];
                    if (self.devicesList.status == 1) {
                        
                        [SVProgressHUD showTitle:NSLocalizedString(@"投喂中", nil) duration:2];
                   
                        NSLog(@"喂食 %ld 份",weight);
                        NSString *data = [NSString stringWithFormat:@"{\"method\":\"control\",\"to\":\"%@\",\"manual_feed\":%ld}",self.bid,weight];
                        [YKBusinessFramework equesSendData:data];
                        
                    }else if (self.devicesList.status == 2){
                        
                        [SVProgressHUD showTitle:NSLocalizedString(@"投喂中", nil) duration:2];
                   
                        __block int timeout = 30*200*5; // 倒计时时间
                        weakSelf.cancelpost = NO;
                        dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
                        weakSelf.wake_up_timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
                        dispatch_source_set_timer(weakSelf.wake_up_timer,dispatch_walltime(NULL, 0),200.0*NSEC_PER_MSEC, 0); //每秒执行
                        dispatch_source_set_event_handler(weakSelf.wake_up_timer, ^{
                            if(weakSelf.cancelpost){ // 倒计时结束，关闭
                                dispatch_source_cancel(weakSelf.wake_up_timer);
                                weakSelf.wake_up_timer = nil;
                                
                                NSLog(@"喂食 %ld 份",weight);
                                NSString *data = [NSString stringWithFormat:@"{\"method\":\"control\",\"to\":\"%@\",\"manual_feed\":%ld}",self.bid,weight];
                                [YKBusinessFramework equesSendData:data];
                                
                            }else{
                                NSString *Str =   [NSString stringWithFormat:@"{\"method\":\"wake_up_t1_r700\",\"from\":\"%@\",\"to\":\"%@\",\"id\":100006071,\"value\": {\"id\":2,\"val\":1}}",[[NSUserDefaults standardUserDefaults] objectForKey:@"EquesUid"],self.bid];
                                [YKBusinessFramework equesSendData:Str];
                                 timeout-=200;
                                if (timeout <= 0) {
                                    dispatch_source_cancel(weakSelf.wake_up_timer);
                                    weakSelf.wake_up_timer = nil;
                                }
                            }
                        });
                         dispatch_resume(weakSelf.wake_up_timer);
                    }
                    
                };
                
               [self presentViewController:feedvc animated:YES completion:nil];
                
            }
            
            
        }
            break;
          
        case 226:
        {

            if (self.is_click_play || self.isSucessFlag) {
                [self hangup:NO];
            }
            
            if(![self.navigationController.topViewController isKindOfClass:[CatMessageVController class]]) {
                CatMessageVController *setting = [[CatMessageVController alloc]init];
                setting.tag = 1;
                setting.bid = self.bid;
               [self.navigationController pushViewController:setting animated:YES];
            }
        
        }
            break;
            
        case 227:
        {

            if (self.is_click_play || self.isSucessFlag) {
                [self hangup:NO];
            }
            
            if(![self.navigationController.topViewController isKindOfClass:[CatMessageVController class]]) {
                CatMessageVController *setting = [[CatMessageVController alloc]init];
                setting.tag = 2;
                setting.bid = self.bid;
               [self.navigationController pushViewController:setting animated:YES];
            }
                
        }
            break;
            
        case 228:
        {
           
            NSLog(@"点击定时");
            if (self.is_click_play || self.isSucessFlag) {
                [self hangup:NO];
            }
            
            CatTimingListVController *addtiming = [[CatTimingListVController alloc]init];
            addtiming.bid = self.bid;
           [self.navigationController pushViewController:addtiming animated:YES];
          
            
        }
            break;

        default:
            break;
    }
}


- (void)start_record
{
    
     self.is_recording = YES;
     NSString *capture = @"cat.mp4";
    
    // 获取Documents文件夹目录
    NSArray  *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask,YES);
    NSString *documentPath = [path objectAtIndex:0];
    // 获取文件管理器
    NSFileManager *fileManager = [NSFileManager defaultManager];
    // 指定新建文件夹路径
    NSString *imageDocPath = [documentPath stringByAppendingPathComponent:@"VideoFile"];
    // 创建ImageFile文件夹
    [fileManager createDirectoryAtPath:imageDocPath withIntermediateDirectories:YES attributes:nil error:nil];
    NSString *newstr = [imageDocPath stringByAppendingFormat:@"/%@",capture];
    NSString *imagePath;
    
    if ([[NSFileManager defaultManager]fileExistsAtPath:newstr]) {
         NSError *error;
        [[NSFileManager defaultManager] removeItemAtPath:newstr error:&error];
        NSLog(@"removeItemAtPath == %@",error);
    }
    
    self.devicesList = [[FBDevicesList bg_find:@"FBDevicesList" where:[NSString stringWithFormat:@"where %@=%@ and %@=%@",bg_sqlKey(@"userName"),bg_sqlValue([Tooles getuserToken]), bg_sqlKey(@"bid"),bg_sqlValue(self.bid)]] firstObject];
    
    NSLog(@"cat angle == %d",self.devicesList.camera_id);
    int angle = 0 ;
    switch (self.devicesList.camera_id) {
        case 0:
        case 3:
        {
            angle = 90;
        }
            break;
        case 5:
        {
            angle = 0;
        }
            break;
        case 4:
        {
            angle = 180;
        }
            break;
            
        default:{
            angle = 270;
        }
            break;
    }
    
    NSLog(@"angle == %d",angle);
    
    if (![[NSFileManager defaultManager]fileExistsAtPath:newstr]) {
        //返回保存图片的路径（图片保存在ImageFile文件夹下）
         imagePath = [imageDocPath stringByAppendingPathComponent:capture];
        [fileManager createFileAtPath:imagePath contents:nil attributes:nil];
        [YKBusinessFramework start_record:640 height:480 path:imagePath degree:angle];
    }else{
        
         NSLog(@"[[NSFileManager defaultManager]fileExistsAtPath:newstr] == %d",[[NSFileManager defaultManager]fileExistsAtPath:newstr]);
        [YKBusinessFramework start_record:640 height:480 path:newstr degree:angle];
         
    }
    
}

- (void)stop_record
{
   [YKBusinessFramework stop_record];
    self.is_recording = NO;
    [SVProgressHUD showWithStatus:NSLocalizedString(@"正在保存", nil)];
     NSString *capture = @"cat.mp4";
    
    // 获取Documents文件夹目录
    NSArray  *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask,YES);
    NSString *documentPath = [path objectAtIndex:0];
    // 获取文件管理器
    NSFileManager *fileManager = [NSFileManager defaultManager];
    // 指定新建文件夹路径
    NSString *imageDocPath = [documentPath stringByAppendingPathComponent:@"VideoFile"];
    // 创建ImageFile文件夹
    [fileManager createDirectoryAtPath:imageDocPath withIntermediateDirectories:YES attributes:nil error:nil];
    NSString *newstr = [imageDocPath stringByAppendingFormat:@"/%@",capture];
    
     dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
         NSData *data = [NSData dataWithContentsOfFile:newstr];
         NSLog(@"cat.mp4 data.length == %ld",data.length);
         if (data.length == 0) {
            [SVProgressHUD showErrorWithStatus:NSLocalizedString(@"保存失败", nil)];
             return;
          }
         [self save:newstr];
     });
    
}


#pragma mark saveVideo detail
- (void)save:(NSString*)urlString{
   
    if ([UIDevice currentDevice].systemVersion.doubleValue >= 11.0) {
        [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
            dispatch_async(dispatch_get_main_queue() , ^{
                if (status == PHAuthorizationStatusNotDetermined  || status == PHAuthorizationStatusRestricted || status == PHAuthorizationStatusDenied) {
                    NSString *name = NSLocalizedString(@"相册权限没开启,请在通用隐私相册里开启叮咚的相册服务", nil);
                     UIAlertView *albumaccessAlertView = [[UIAlertView alloc] initWithTitle:name message:nil delegate:self cancelButtonTitle:NSLocalizedString(@"取消", nil) otherButtonTitles:NSLocalizedString(@"确定", nil), nil];
                     albumaccessAlertView.tag = 202;
                    [albumaccessAlertView show];
                    return;
                }
            });
        }];
    }else{
        if (![self checkAlbumAccess]) {
            return;
        }
    }
    
    __block NSString *msg = nil ;
    ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];

    [library writeVideoAtPathToSavedPhotosAlbum:[NSURL fileURLWithPath:urlString]
                                completionBlock:^(NSURL *assetURL, NSError *error) {
            if (error) {
                  msg = NSLocalizedString(@"save failure", nil);
                 [SVProgressHUD showTitle:msg duration:2];
             } else {
                  msg = NSLocalizedString(@"Save to phone album", nil);
                 [SVProgressHUD showTitle:msg duration:2];
                 NSLog(@"error = %@",error);
                 NSLog(@"assetURL = %@",assetURL);
                 NSLog(@"fileURLWithPath = %@",[NSURL fileURLWithPath:urlString]);
            }
    }];
}

- (BOOL )checkAlbumAccess{
    if (![Tooles albumAccess]) {
        NSString * name = NSLocalizedString(@"相册权限没开启,请在通用隐私相册里开启叮咚的相册服务", nil);
        UIAlertView *albumAcessAlert = [[UIAlertView alloc] initWithTitle:name message:nil delegate:self cancelButtonTitle:NSLocalizedString(@"取消", nil) otherButtonTitles:NSLocalizedString(@"确定", nil), nil];
         albumAcessAlert.tag = 202;
        [albumAcessAlert show];
        return NO;
    }else{
        return YES;
    }
   
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    switch (alertView.tag) {
        case 202:
            if (buttonIndex == 1) {
                {
                    NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
                    [[UIApplication sharedApplication] openURL:url];
                }
            }else{
                
            }
            break;

        case 704:
        {
            if (buttonIndex == 1)
            {
                void (^mysetting)() = ^(){

                     NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
                    [[UIApplication sharedApplication] openURL:url];
                };
                mysetting();
            }
        }
            break;
        default:
            break;
    }
}




- (void)removeFourButton
{
    if (self.iSAddButton) {
        for (int i = 0; i < 8; i++) {
            UIButton *sender = (UIButton*)[self.view viewWithTag:222+i];
            [sender removeFromSuperview];
            sender = nil;
        }
    }
}


- (UIImageView*)animationImageView
{
     if (!_animationImageView) {
          _animationImageView = [[UIImageView alloc]init];
        [self.view addSubview:_animationImageView];
        [_animationImageView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(self.view.mas_centerX);
            make.bottom.equalTo(self.contectingLabel.mas_top);
            make.width.height.mas_equalTo(100);
        }];
         [self.view bringSubviewToFront:_animationImageView];
    }
    return _animationImageView;
}

- (UILabel*)contectingLabel
{
     if (!_contectingLabel) {
         _contectingLabel = [[UILabel alloc]init];
        [_contectingLabel sizeToFit];
         _contectingLabel.font = [UIFont fontWithName:@"PingFangSC-Regular" size:15.0];
         _contectingLabel.textColor = [HexChangeRGB colorWithHexString:@"#ffffff"];
        [_topVideoContrainView addSubview:_contectingLabel];
        [_contectingLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.equalTo(_topVideoContrainView.mas_centerY);
            make.centerX.equalTo(_topVideoContrainView.mas_centerX);
        }];
    }
    return _contectingLabel;
}



- (BOOL)shouldAutorotate {
    return NO;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation{
    return NO;
}


- (UIImage*)createCaptureView:(UIImage*)image
{
    
    UIImage *saveImage = image;
    UIView *view1 = [[UIView alloc]init];
    view1.frame = CGRectMake(0,0,saveImage.size.height,saveImage.size.width);
    UIImageView *imageview = [[UIImageView alloc]init];
    [view1 addSubview:imageview];
    [imageview mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(saveImage.size.height);
        make.width.mas_equalTo(saveImage.size.width);
        make.centerX.equalTo(view1.mas_centerX);
        make.centerY.equalTo(view1.mas_centerY);;
    }];
    imageview.image = saveImage;
    
    CGAffineTransform transform = CGAffineTransformIdentity;
    
    if (self.devicesList.camera_id > 0 && self.devicesList.camera_id != 4) {
        if (self.devicesList.camera_id == 3) {
            transform = CGAffineTransformRotate(transform,M_PI_2);
        }else if ( self.devicesList.camera_id == 5) {
            
        }else{
            transform = CGAffineTransformRotate(transform, -M_PI_2);
        }
    }else{
        if ( self.devicesList.camera_id == 4) {
            transform = CGAffineTransformRotate(transform, M_PI);
        }else{
            transform = CGAffineTransformRotate(transform, M_PI_2);
        }
    }
    
    
     imageview.transform = transform;
    [self.view insertSubview:view1 atIndex:0];
    
    UIImage *imsge = [self captureView:view1];
    
    view1.hidden = YES;
    return imsge;
    
}

#pragma mark: view获得截图 生成图片
-(UIImage*)captureView:(UIView *)theView{
    CGRect rect = theView.frame;
    if ([theView isKindOfClass:[UIScrollView class]]) {
        rect.size = ((UIScrollView *)theView).contentSize;
    }
    UIGraphicsBeginImageContext(rect.size);
    UIGraphicsBeginImageContextWithOptions(rect.size, NO, [UIScreen mainScreen].scale);
    CGContextRef context = UIGraphicsGetCurrentContext();
    [theView.layer renderInContext:context];
    UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return img;
}

    
    

#pragma mark VL0抓拍保存到本地
- (void)saveImageToPhotos:(UIImage*)savedImage
{
    if ([UIDevice currentDevice].systemVersion.doubleValue >= 11.0) {
   
        [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
            
            dispatch_async(dispatch_get_main_queue() , ^{
                if (status == PHAuthorizationStatusNotDetermined  || status == PHAuthorizationStatusRestricted || status == PHAuthorizationStatusDenied) {
                    UIAlertView *albumaccessAlertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"相册权限没开启,请在通用隐私相册里开启叮咚的相册服务", nil) message:nil delegate:self cancelButtonTitle:NSLocalizedString(@"取消", nil) otherButtonTitles:NSLocalizedString(@"确定", nil), nil];
                     albumaccessAlertView.tag = 704;
                    [albumaccessAlertView show];
                    return;
                }
            });
        }];
    }else{
        
        [self checkAlbumAccess];
        
    }
    
    UIImageWriteToSavedPhotosAlbum(savedImage, self, @selector(image:didFinishSavingWithError:contextInfo:), NULL);
}

// 指定回调方法
- (void)image: (UIImage *) image didFinishSavingWithError: (NSError *) error contextInfo: (void *) contextInfo
{
    if(!error)
    {
        [SVProgressHUD showSuccessWithStatus:NSLocalizedString(@"保存到相册成功", nil)];
    }
    else
    {
        [SVProgressHUD showErrorWithStatus:NSLocalizedString(@"保存失败", nil)];
    }

}

- (void)getdevices
{
    
    [AFNHTTPSRequest httpsRequestWithUrl:[YKBusinessFramework get_shadow_settings:self.bid lastUpdate:0] errorHint:^(id errorData) {
        
        NSLog(@"get_shadow_settings  errorData-->%@ ",errorData);
    } result:^(id data) {

        NSLog(@"get_shadow_settings  data-->%@ ",data);
        if ([[data objectForKey:@"code"] intValue] == 0){
            
            NSDictionary *settingDict = [data objectForKey:@"settings"];
            
            FBDevicesList *devicesList = [[FBDevicesList bg_find:@"FBDevicesList" where:[NSString stringWithFormat:@"where %@=%@ and %@=%@",bg_sqlKey(@"userName"),bg_sqlValue([Tooles getuserToken]),bg_sqlKey(@"bid"),bg_sqlValue(self.bid)]] firstObject];
      
            if (devicesList) {
                
        
                if ([settingDict objectForKey:@"disturb_start_time"]) {
                    devicesList.disturb_start_time = [settingDict objectForKey:@"disturb_start_time"];
                }
    
                if ([settingDict objectForKey:@"disturb_end_time"]) {
                    devicesList.disturb_end_time = [settingDict objectForKey:@"disturb_end_time"];
                }
                
                if ([settingDict objectForKey:@"disturb_status"]) {
                    devicesList.disturb_status = [[settingDict objectForKey:@"disturb_status"] intValue];
                }
                if ([settingDict objectForKey:@"voice_status"]) {
                    devicesList.voice_status = [[settingDict objectForKey:@"voice_status"] intValue];
                }
                if ([settingDict objectForKey:@"voice_count"]) {
                    devicesList.voice_count = [[settingDict objectForKey:@"voice_count"] intValue];
                }
             
                if ([settingDict objectForKey:@"voice_index"]) {
                    devicesList.voice_index = [[settingDict objectForKey:@"voice_index"] intValue];
                }
                
        
                if ([settingDict objectForKey:@"alarm_enable"]) {
                    devicesList.alarm_enable = [[settingDict objectForKey:@"alarm_enable"] boolValue];
                }
                if ([settingDict objectForKey:@"alm_mod"]) {
                    devicesList.alm_mod = [[settingDict objectForKey:@"alm_mod"] intValue];
                }
                if ([settingDict objectForKey:@"video_time"]) {
                    devicesList.video_time = [[settingDict objectForKey:@"video_time"] intValue];
                }
    
            
//                {
//                    "alive_start_time" = "09:00";
//                    "alive_stop_time" = "18:00";
//                    "alm_mod" = 0;
//                    "lcd_timeout" = 10;
//                    overturn = 0;
//                    "show_open_lock_button" = 1;
//                    "time_zone" = "+480";
//                    "video_time" = 5;
//                    "voice_count" = 0;
//                    "voice_index" = 0;
//                    "voice_status" = 0;
//                    "work_mode" = 0;
//                }
                if ([devicesList bg_saveOrUpdate]) {
                }

            }
        }
    }];
    
    [AFNHTTPSRequest httpsRequestWithUrl:[YKBusinessFramework get_shadow_state:self.bid] errorHint:^(id StaterrorData) {
        NSLog(@"获取状态失败-->%@",StaterrorData);
    } result:^(id StateData) {
        NSLog(@"获取状态 -- >%@",StateData);
        if ([[StateData objectForKey:@"code"] intValue] == 0){
            NSDictionary *stateDict = [StateData objectForKey:@"state"];
            FBDevicesList *stateInfo = [[FBDevicesList bg_find:@"FBDevicesList" where:[NSString stringWithFormat:@"where %@=%@ and %@=%@",bg_sqlKey(@"userName"),bg_sqlValue([Tooles getuserToken]),bg_sqlKey(@"bid"),bg_sqlValue(self.bid)]] firstObject];
            if (stateInfo) {
                stateInfo.wifi_ssid = [stateDict objectForKey:@"wifi_ssid"];
                stateInfo.wifi_rssi = [stateDict objectForKey:@"wifi_rssi"];
                stateInfo.wifi_level = [stateDict objectForKey:@"wifi_level"];
                stateInfo.camera_id = [[stateDict objectForKey:@"camera_id"] intValue];
                stateInfo.brand_id = [[stateDict objectForKey:@"brand_id"] intValue];
                if ([stateDict objectForKey:@"power_mode"]) {
                    stateInfo.power_mode = [[stateDict objectForKey:@"power_mode"] intValue];
                }
                stateInfo.vnum = [stateDict objectForKey:@"vnum"];
                stateInfo.usb_vnum = [stateDict objectForKey:@"usb_vnum"];
                stateInfo.videocall_width = [[stateDict objectForKey:@"videocall_width"] intValue];
                stateInfo.videocall_height = [[stateDict objectForKey:@"videocall_height"] intValue];
                stateInfo.function_support = [stateDict objectForKey:@"function_support"];
                if ([stateInfo bg_saveOrUpdate]) {
                    NSLog(@"信息更新成功");
                }
            }
        }
    }];
}


@end
